<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>网格员管理</span>
        <div style="margin-top: 20px">
          <el-radio-group v-model="queryParams.sex">
            <el-radio-button :label="0">男</el-radio-button>
            <el-radio-button :label="1">女</el-radio-button>
          </el-radio-group>
        </div>
        <div class="mt-4">
          <el-input v-model="queryParams.telephone" placeholder="请输入联系方式" class="input-with-select">
            <template #append>
              <el-button @click="fetchData" :icon="Search" />
            </template>
          </el-input>
        </div>
        <div class="mt-4">
          <el-input v-model="queryParams.name" placeholder="请输入网格员姓名" class="input-with-select">
            <template #append>
              <el-button @click="fetchData" :icon="Search" />
            </template>
          </el-input>
        </div>
      </div>
    </template>
    <el-config-provider :locale="locale">
      <el-table :data="tableData" style="width: 100%" :table-layout="tableLayout" :row-class-name="tableRowClassName">
        <el-table-column prop="autoId" label="网格员编号" width="100px" align="center" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别">
          <template #default="scope">
            <p v-if="scope.row.sex == 0">男</p>
            <p v-if="scope.row.sex == 1">女</p>
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="出生日期" />
        <el-table-column prop="telephone" label="联系电话" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-popconfirm
              width="320"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              :title="'确定要注销吗?'"
              @confirm="logout(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">注销</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination
        v-model:current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="prev, pager, next"
        :total="total"
        @current-change="handlePageChange"
      /> -->

      <!-- 分页 -->
      <div style="text-align: -webkit-center">
        <div style="margin-right: 30px">
          <el-config-provider :locale="locale">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :small="small"
              :page-sizes="[1, 6, 7, 8, 9, 10]"
              :background="background"
              layout="prev, pager, next, jumper,sizes,total"
              v-model:total="total"
              @current-change="handlePageChange"
              @size-change="handlePageChange"
              style="width: max-content; margin-top: 50px"
            />
          </el-config-provider>
        </div>
      </div>
    </el-config-provider>
  </el-card>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElNotification } from 'element-plus'
import { InfoFilled, Search, Plus } from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
import $axios from '../utils/axios'
import AddressSelect from '../supervisor/addressSelect.vue'

const language = ref('zh-cn')
const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en))

const tableLayout = ref('auto')
const total = ref(1000)

// ----------新增----------
//打开对话框
const addDialogVisible = ref(false)

//定义日历的禁用日期计算属性
const hiredateDisabledDate = (time) => time.getTime() > new Date().getTime()

// 分页和查询参数
const queryParams = reactive({
  sex: null,
  telephone: '',
  name: '',
  pageNum: 1,
  pageSize: 10
})

const fetchData = async () => {
  const path = '/api/admin/queryGridMan'
  try {
    console.log('Fetching data with params:', { ...queryParams })
    const response = await $axios.post(path, { ...queryParams }, {})
    const res = response.data
    if (res.code === '200') {
      // 为每条数据添加 autoId 字段
      tableData.value = res.data.list.map((item, index) => ({
        ...item,
        autoId: (queryParams.pageNum - 1) * queryParams.pageSize + index + 1
      }))
      total.value = res.data.total
    } else {
      console.error('Unexpected response code:', res.code)
    }
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}

const handlePageChange = (page) => {
  fetchData()
}

//向子组件传值：宽度
//接受子组件 省市区选择组件 的选择结果
let selectWidth = '150px'
let labelWidth = '50px'
const grid = ref({
  province: { id: '', name: '', leaderId: '' },
  city: { id: '', name: '', leaderId: '' },
  town: { id: '', name: '', leaderId: '' }
})

const form = ref({})

//----------调动----------
const transDialogVisible = ref(false)
const transForm = ref({})
const transGrid = ref({
  province: { id: '', name: '', leaderId: '' },
  city: { id: '', name: '', leaderId: '' },
  town: { id: '', name: '', leaderId: '' }
})
const selectChanged1 = (f) => {
  transGrid.value = f
  console.log(transGrid.value)
  transForm.value.pId = transGrid.value.province.id
  transForm.value.cId = transGrid.value.city.id
  transForm.value.tId = transGrid.value.town.id
}

//斑马条
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 1 ? 'success-row' : ''
}
//初始化
const tableData = ref([])
const init = async () => {
  //   const path = '/user/findGrid'
  //   const { data: res } = await $axios.get(path)
  //   if (res.code === 200) {
  //     tableData.value = res.result
  //   }
  fetchData()
}
init()
//搜索

//按状态筛选
// const filterState = (value, row) => {
//   return row.state === value
// }
//注销
// 注销
const logout = async (index, row) => {
  console.log(index, row)
  console.log(row.uid)

  // 构建带有 uid 的路径
  const path = `/api/admin/delete/${row.uid}`

  // 发送 POST 请求，无需发送其他数据
  const { data: res } = await $axios.post(path)

  // 处理响应
  if (res.code === '00000') {
    ElNotification({
      title: '成功',
      message: '已将' + row.name + '账号注销',
      type: 'success'
    })
    fetchData()
  } else if (res.code === 103) {
    ElNotification({
      title: '失败',
      message: '修改失败',
      type: 'error'
    })
  }
}
</script>

<style scoped>
.box-card {
  width: 99%;
  height: 95%;
  margin-top: 12px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>

<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
